<template>
  <div class="order-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>订单管理</span>
        <!-- <el-button style="float: right; padding: 3px 0" type="text" @click="handleExport">导出订单</el-button> -->
      </div>

      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="queryParams.machineName" placeholder="请输入设备名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="未支付" value="unpaid"></el-option>
            <el-option label="已完成" value="paid"></el-option>
            <el-option label="已退款" value="refunded"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker v-model="dateRange" type="daterange" align="right" unlink-panels range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="orderList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="orderNo" label="订单号" width="180">
        </el-table-column>
        <el-table-column prop="goodsName" label="商品名称">
        </el-table-column>
        <el-table-column prop="machineName" label="设备名称">
        </el-table-column>
        <el-table-column label="商品图片" width="120">
          <template slot-scope="scope">
            <el-image style="width: 60px; height: 60px" :src="scope.row.goodsImage"
              :preview-src-list="[scope.row.goodsImage]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="金额" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="80">
        </el-table-column>
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120">
          <template slot-scope="scope">
            {{ scope.row.paymentMethod | paymentMethodFilter }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | statusFilter">{{ scope.row.status | statusTextFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="180">
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleDetail(scope.row)">详情</el-button>
            <el-button size="mini" type="danger" v-if="scope.row.status === 'paid'"
              @click="handleRefund(scope.row)">退款</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum" :page-sizes="[10, 20, 30, 50]" :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="detailVisible" width="50%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ currentOrder.goodsName }}</el-descriptions-item>
        <el-descriptions-item label="商品图片">
          <el-image style="width: 100px; height: 100px" :src="currentOrder.goodsImage"
            :preview-src-list="[currentOrder.goodsImage]">
          </el-image>
        </el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ currentOrder.machineName }}</el-descriptions-item>
        <el-descriptions-item label="单价">¥{{ currentOrder.price }}</el-descriptions-item>
        <el-descriptions-item label="数量">{{ currentOrder.quantity }}</el-descriptions-item>
        <el-descriptions-item label="总金额">¥{{ currentOrder.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ currentOrder.paymentMethod | paymentMethodFilter }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="currentOrder.status | statusFilter">{{ currentOrder.status | statusTextFilter }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ currentOrder.createTime }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ currentOrder.payTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="退款时间">{{ currentOrder.refundTime || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderList, refundOrder, exportOrder } from '@/api/order'

export default {
  name: 'Order',
  filters: {
    statusFilter (status) {
      const statusMap = {
        'paid': 'success',
        'unpaid': 'danger',
        'refunded': 'info'
      }
      return statusMap[status]
    },
    statusTextFilter (status) {
      const statusTextMap = {
        'paid': '已完成',
        'unpaid': '未支付',
        'refunded': '已退款'
      }
      return statusTextMap[status]
    },
    paymentMethodFilter (method) {
      const methodMap = {
        'alipay': '支付宝',
        'wechat': '微信支付',
        'cash': '现金'
      }
      return methodMap[method] || method
    }
  },
  data () {
    return {
      queryParams: {
        orderNo: '',
        goodsName: '',
        machineName: '',
        status: '',
        startTime: '',
        endTime: '',
        pageNum: 1,
        pageSize: 10
      },
      dateRange: [],
      orderList: [],
      total: 0,
      loading: false,
      detailVisible: false,
      currentOrder: {}
    }
  },
  created () {
    this.getList()
  },
  methods: {
    getList () {
      this.loading = true

      // 处理时间范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.startTime = this.dateRange[0]
        this.queryParams.endTime = this.dateRange[1]
      } else {
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
      }

      getOrderList(this.queryParams).then(response => {
        this.orderList = response.data.list
        this.total = response.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery () {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery () {
      this.queryParams = {
        orderNo: '',
        goodsName: '',
        machineName: '',
        status: '',
        startTime: '',
        endTime: '',
        pageNum: 1,
        pageSize: 10
      }
      this.dateRange = []
      this.getList()
    },
    handleSizeChange (val) {
      this.queryParams.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.queryParams.pageNum = val
      this.getList()
    },
    handleDetail (row) {
      this.currentOrder = Object.assign({}, row)
      this.detailVisible = true
    },
    handleRefund (row) {
      this.$confirm('确认要退款吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        refundOrder(row.orderNo).then(response => {
          this.$message({
            type: 'success',
            message: '退款成功!'
          })
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退款'
        })
      })
    },
    handleExport () {
      // 处理时间范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.startTime = this.dateRange[0]
        this.queryParams.endTime = this.dateRange[1]
      } else {
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
      }

      exportOrder(this.queryParams).then(response => {
        const blob = new Blob([response.file], { type: 'application/vnd.ms-excel' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `订单数据_${new Date().toLocaleDateString()}.xlsx`
        link.click()
        window.URL.revokeObjectURL(url)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.order-container {
  padding: 20px;

  .search-form {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}
</style>